import Vue from "vue";
import Vuex from "vuex";
//请求用户菜单的api
import * as permissionApi from "../api/permission"
//所有的路由配置
import allRoutes from "../router/allRoutes"
//工具函数 计算用户的路由
import recursionRoutes from '../utils/recursionRoutes'
//引入需要动态添加的路由
import dynamicRoutes from "../router/dynamicRoutes"
//引入路由对象
import router from "../router"
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    //用户信息
    userInfo: {},
    //用户菜单
    sideMenu: []
  },
  mutations: {
    //设置用户信息
    SET_USERINFO(state, payload) {
      state.userInfo = payload
    },
    //设置用户菜单
    SET_SIDEMENU(state, payload) {
      //还需要动态的将路由添加到项目中

      //所有的动态路由都要成为 /路径这个路由配置的children,所以我们需要先把这个对象找出来
      let target = dynamicRoutes.find(route => route.path === "/");
      //将用户路由添加给 /配置的children 
      target.children = payload
      //动态的将dynamicRoutes添加到路由的配置当中
      //核心方法就是addRoutes(Array<routerConfig>)
      //新版方法叫做addRoute({})
      // router.addRoutes(dynamicRoutes)
      dynamicRoutes.forEach(route => {
        router.addRoute(route)
      })
      //给侧边菜单数据赋值
      state.sideMenu = payload;
    }
  },
  actions: {
    //需要异步获取用户菜单
    async FETCH_MENULIST({ commit }) {
      let res = await permissionApi.getMenulistApi();
      // console.log(res)

      //计算用户路由
      let userRouter = recursionRoutes(allRoutes, res.data.menuList)

      commit("SET_SIDEMENU", userRouter)
    }
  },
  modules: {},
});
